package socket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 带图形界面的聊天客户端
 */
public class ClientGUI {
    private JFrame frame;
    private JTextArea chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private Socket socket;
    private OutputStream out;
    private Thread receiveThread;

    public ClientGUI() {
        // 初始化界面组件
        frame = new JFrame("聊天客户端");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setLocationRelativeTo(null);

        // 聊天记录显示区域
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        JScrollPane scrollPane = new JScrollPane(chatArea);

        // 输入区域面板
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputField = new JTextField();
        sendButton = new JButton("发送");

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        // 添加组件到主窗口
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.getContentPane().add(inputPanel, BorderLayout.SOUTH);

        // 注册事件监听器
        sendButton.addActionListener(new SendButtonListener());
        inputField.addActionListener(new SendButtonListener());

        // 连接到服务器
        connectToServer();
    }

    private void connectToServer() {
        try {
            chatArea.append("正在连接服务器...\n");
            socket = new Socket("localhost", 8088);
            out = socket.getOutputStream();
            chatArea.append("已连接到服务器\n");

            // 启动接收消息的线程
            receiveThread = new Thread(new ReceiveMessageTask());
            receiveThread.start();
        } catch (IOException e) {
            chatArea.append("连接服务器失败: " + e.getMessage() + "\n");
            e.printStackTrace();
        }
    }

    private void sendMessage(String message) {
        if (message == null || message.trim().isEmpty()) {
            return;
        }

        try {
            // 发送消息到服务器
            byte[] data = message.getBytes(StandardCharsets.UTF_8);
            out.write(data.length);
            out.write(data);

            // 在本地显示自己发送的消息
            chatArea.append("我: " + message + "\n");
            inputField.setText("");
        } catch (IOException e) {
            chatArea.append("发送消息失败: " + e.getMessage() + "\n");
            e.printStackTrace();
        }
    }

    private class SendButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String message = inputField.getText();
            sendMessage(message);
        }
    }

    private class ReceiveMessageTask implements Runnable {
        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                while (true) {
                    int length = in.read();
                    if (length == -1) {
                        break;
                    }

                    byte[] buffer = new byte[length];
                    int bytesRead = 0;
                    while (bytesRead < length) {
                        int count = in.read(buffer, bytesRead, length - bytesRead);
                        if (count == -1) {
                            break;
                        }
                        bytesRead += count;
                    }

                    if (bytesRead == length) {
                        String message = new String(buffer, StandardCharsets.UTF_8);
                        chatArea.append(message + "\n");

                        // 滚动到底部
                        SwingUtilities.invokeLater(() -> {
                            chatArea.setCaretPosition(chatArea.getDocument().getLength());
                        });
                    }
                }
            } catch (IOException e) {
                chatArea.append("与服务器断开连接\n");
            } finally {
                try {
                    if (socket != null && !socket.isClosed()) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void show() {
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ClientGUI client = new ClientGUI();
            client.show();
        });
    }
}